import { CLIError } from '../types';

export function validateEmail(email: string): boolean {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
}

export function validatePhone(phone: string): boolean {
  const phoneRegex = /^1[3-9]\d{9}$/;
  return phoneRegex.test(phone);
}

export function isEmailOrPhone(input: string): 'email' | 'phone' | null {
  if (validateEmail(input)) return 'email';
  if (validatePhone(input)) return 'phone';
  return null;
}

export function validateProjectName(name: string): boolean {
  const nameRegex = /^[a-zA-Z0-9-_]+$/;
  return nameRegex.test(name) && name.length >= 2 && name.length <= 50;
}

export function validateModuleName(name: string): boolean {
  const nameRegex = /^[a-zA-Z0-9-_\.]+$/;
  return nameRegex.test(name) && name.length >= 2 && name.length <= 100;
}

export function validateEnvironmentName(name: string): boolean {
  const nameRegex = /^[a-zA-Z0-9-_]+$/;
  return nameRegex.test(name) && name.length >= 2 && name.length <= 30;
}

export function validateVersion(version: string): boolean {
  const versionRegex = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/;
  return versionRegex.test(version);
}

export function requireAuth(): void {
  const { config } = require('../services/config');
  const token = config.getToken();
  if (!token) {
    throw new CLIError('Not authenticated. Please run "cm login" first.');
  }
}

export function requireProject(): string {
  const { config } = require('../services/config');
  const project = config.getCurrentProject();
  if (!project) {
    throw new CLIError('No project selected. Please run "cm project use <name>" first.');
  }
  return project;
}